﻿using EMS.system.Common;
using EMS.system.Entityies.WarehouseManagement.ProductionRequisitionModel;
using EMS.system.Entityies.WarehouseManagement.SalesReturnModel;
using EMS.system.IEntityAppService.WarehouseManagement.MaterialRequisition;
using EMS.system.IEntityAppService.WarehouseManagement.SalesReturns;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace EMS.system.EntityAppService.WarehouseManagement.SalesReturns
{
    public class SalesReturnsAppService : systemAppService, ISalesReturnsAppService
    {
        private readonly IRepository<SalesReturn, int> _repository;
        public SalesReturnsAppService(IRepository<SalesReturn, int> repository)
        {
            _repository = repository;
        }


        public async Task<int> AddSalesReturns(SalesReturnsAppServiceDTO dto)
        {
            var productionRequisition = dto.MapTo<SalesReturn>();
            await _repository.InsertAsync(productionRequisition);
            return 1;
        }

        public PagedResult GetSalesReturns(string? code, string? name, int page = 1, int limit = 2)
        {
            var predicate = PredicateBuilder.New<SalesReturn>(true);
            if (!string.IsNullOrEmpty(code))
            {
                predicate = predicate.And(m => m.ReturnID.Contains(code));
            }
            if (!string.IsNullOrEmpty(name))
            {
                predicate = predicate.And(m => m.ReturnOrderName.Contains(name));
            }
            var dto = _repository.GetListAsync(predicate).Result;
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / limit);
            result.PageSize = limit;
            result.CurrentPage = page;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((page - 1) * limit).Take(limit).AsQueryable();
            return result;
        }

        public async Task<int> DeleteSalesReturns(int id)
        {
            await _repository.DeleteAsync(id);
            return 1;
        }

        public async Task<SalesReturn> GetSalesReturnsById(int id)
        {
            var model = await _repository.FirstOrDefaultAsync(x => x.Id == id);
            return model;
        }
        public async Task<int> UpdateSalesReturns(SalesReturnsAppServiceDTO dto)
        {
            var model = dto.MapTo<SalesReturn>();
            await _repository.UpdateAsync(model);
            return 1;
        }
    }
}
